﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.IO;

namespace SBLib.Common.EmailKS
{
    public class EmailFuncKS
    {
        private SmtpClient _client;
        private MailMessage _message;
        private bool _enableSsl = false;

        public EmailFuncKS(string HostName, int PortNo, string UserID, string Password)
        {
            _client = new SmtpClient(HostName, PortNo);
           _client.Credentials = new NetworkCredential(UserID ,Password);

           _message = new MailMessage();
        }

        //private string BodyTemplateLocation { get; set; }
        private Dictionary<string, string> Replacements { get; set; }

        //public KSMailMessage
        //{

        //}
        public void FromEmail(string emailAddress, string displayName = "")
        {
            _message.From = new MailAddress(emailAddress, displayName);
        }


        public void ToEmail(string emailAddress, string displayName = "")
        {
            _message.To.Add(new MailAddress(emailAddress, displayName));
        }

        public void ToEmailList(List<MailAddress> mailAddresses)
        {
            foreach (MailAddress address in mailAddresses)
            {
                _message.To.Add(address);
            }
        }


        public void CcEmail(string emailAddress, string displayName = "")
        {
            _message.CC.Add(new MailAddress(emailAddress, displayName));
        }

        public void CcEmailList(List<MailAddress> mailAddresses)
        {
            foreach (MailAddress address in mailAddresses)
            {
                _message.CC.Add(address);
            }
        }

        public void BccEmail(string emailAddress, string displayName = "")
        {
            _message.Bcc.Add(new MailAddress(emailAddress, displayName));
        }

        public void BccEmailList(List<MailAddress> mailAddresses)
        {
            foreach (MailAddress address in mailAddresses)
            {
                _message.Bcc.Add(address);
            }
        }

        public void SubjectName(string subject)
        {
            _message.Subject = subject;
        }

        public void MailBody(string emailBody, bool isHtml = true)
        {
            _message.Body = emailBody;
            _message.IsBodyHtml = isHtml;
        }


        public void IncludeTemplate(string fileName, bool isHtml = true)
        {
            try
            {
                if (fileName.StartsWith("~"))
                {
                    var baseDir = System.AppDomain.CurrentDomain.BaseDirectory;
                    fileName = Path.GetFullPath(baseDir + fileName.Replace("~", ""));
                }

                using (StreamReader reader = File.OpenText(fileName))
                {
                    _message.Body = reader.ReadToEnd();
                }

                _message.IsBodyHtml = isHtml;
            }
            catch (Exception)
            {
                _message.Body = "";
            }

        }


        public void AttachFile(Attachment attachment)
        {
            try
            {
                if (!_message.Attachments.Contains(attachment))
                    _message.Attachments.Add(attachment);
            }
            catch (Exception)
            {
            }

        }

        public void AttachFileList(List<Attachment> attachments)
        {
            try
            {
                foreach (var attachment in attachments.Where(attachment => !_message.Attachments.Contains(attachment)))
                {
                    _message.Attachments.Add(attachment);
                }
            }
            catch (Exception)
            {
            }

        }

        public void ReplaceField(string key, string value)
        {
            try
            {
                Replacements.Add(key, value);
            }
            catch (Exception)
            {

            }
          
        }


        public void PrepateEmailBody()
        {
            try
            {
                if (!String.IsNullOrEmpty(_message.Body))
                {
                    if (Replacements != null)
                    {
                        foreach (string key in Replacements.Keys)
                        {
                            string _val = Replacements[key];
                            _message.Body = _message.Body.Replace(key, _val);
                        }
                    }

                }
            }
            catch (Exception)
            {
                
            }
            

        }

        public void UseSSL()
        {
            _enableSsl = true;
        }

        public void SendEmail()
        {
            try
            {
                PrepateEmailBody();
                _client.EnableSsl = _enableSsl;
                _client.Send(_message);

            }
            catch (Exception)
            {

            }
            finally 
            {
                _message.Dispose();
                _client.Dispose();
            }
        }


        public void SendEmailAsync(SendCompletedEventHandler callback, object token = null)
        {
            //A MailMessage object must be disposed!
            try
            {
                PrepateEmailBody();
                _client.EnableSsl = _enableSsl;
                _client.SendCompleted += callback;
                _client.SendAsync(_message, _message.To.ToString());


                //_client.SendAsyncCancel()
                
            }
            catch (Exception)
            {
                
            }
            finally 
            {
               // _message.Dispose();
                //_client.Dispose();
            }
   
        }
    }
}
